package com.lxw.nonghe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxw.nonghe.entity.Family;
import com.lxw.nonghe.mapper.FamilyMapper;
import com.lxw.nonghe.service.FamilyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 家庭档案表 服务实现类
 * </p>
 *
 * @author lxw
 * @since 2025-04-17
 */
@Service
public class FamilyServiceImpl extends ServiceImpl<FamilyMapper, Family> implements FamilyService {

    @Override
    public Page<Family> getFamilyPage(int current, int size,
        String householder, String address, String registrar,
        Integer population, Integer agriculturalPopulation) {
        Page<Family> page = new Page<>(current, size);
        IPage<Family> iPage = baseMapper.selectFamilyPage(page, householder, address,
            registrar, population, agriculturalPopulation);
        return (Page<Family>) iPage;
    }

    @Override
    public Family getFamilyByHouseholder(String householder) {
        return this.lambdaQuery().eq(Family::getHouseholder,householder).one();
    }

    @Override
    public Page<Family> queryFamily(Family queryFamily, int current, int size) {
        // 参数校验
        if (current < 1) {
            current = 1;
        }
        if (size < 1 || size > 100) {
            size = 10;
        }

        // 构建查询条件
        LambdaQueryWrapper<Family> wrapper = new LambdaQueryWrapper<>();

        // 精确查询条件
        wrapper.eq(queryFamily.getFamilyId() != null,
                        Family::getFamilyId, queryFamily.getFamilyId())
                .eq(queryFamily.getPopulation() != null,
                        Family::getPopulation, queryFamily.getPopulation())
                .eq(queryFamily.getAgriculturalPopulation() != null,
                        Family::getAgriculturalPopulation, queryFamily.getAgriculturalPopulation());

        // 模糊查询条件（String类型字段）
        wrapper.like(StringUtils.isNotBlank(queryFamily.getHouseholder()),
                        Family::getHouseholder, queryFamily.getHouseholder())
                .like(StringUtils.isNotBlank(queryFamily.getAddress()),
                        Family::getAddress, queryFamily.getAddress())
                .like(StringUtils.isNotBlank(queryFamily.getRegistrar()),
                        Family::getRegistrar, queryFamily.getRegistrar());

        // 添加排序（按创建时间降序）
        wrapper.orderByDesc(Family::getCreateTime);

        // 执行分页查询
        Page<Family> page = new Page<>(current, size);
        return this.page(page, wrapper);
    }
}
